package com.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.constant.MessageConstant;
import com.constant.RedisConstant;
import com.dao.CheckGroupDao;
import com.dao.SetmealDao;
import com.entity.PageResult;
import com.entity.QueryPageBean;
import com.entity.Result;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.pojo.CheckGroup;
import com.pojo.Setmeal;
import com.service.SetmealService;
import com.utils.QiniuUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = com.service.SetmealService.class)
@Transactional
public class  SetmealServiceImpl implements SetmealService {
    @Autowired
    private CheckGroupDao checkGroupDao;
    @Autowired
    private SetmealDao setmealDao;
    @Autowired
    private JedisPool jedisPool;
    /*引入静态核心类*/
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    /*引入静态生成路径*/
    @Value("${out_put_path}")
    //TODO 此处有错误
    private String outPutPath;//="F:/develop/health_parent/health_mobile/src/main/webapp/pages";

    //<!--//查询所有的检查组数据,不使用分页助手-->
    @Override
    public Result findCheckGroups() {
        List<CheckGroup> checkGroups = checkGroupDao.findCheckGroups();
        return new Result(true, "查询检查组成功", checkGroups);
    }

    //<!--新增套餐,业务层次还要新增与检查组的中间表-->
    @Override
    public Result addSetmeal(Setmeal setmeal, Integer[] list) {
        //校验
        if (setmeal == null || list == null || list.length < 0) {
            return new Result(false, "黑客入侵抓紧修复");
        }
        Result result = null;
        try {
            setmealDao.addSetmeal(setmeal);
            setmealDao.addSetmealAddCheckGroup(list, setmeal.getId());
            result = new Result(true, MessageConstant.ADD_SETMEAL_SUCCESS);
            //新增成功后吧新增后的图片名称存入到到小容器中
            saveRedis(setmeal.getImg());
        } catch (Exception e) {
            e.printStackTrace();
            result = new Result(false, MessageConstant.ADD_SETMEAL_FAIL);
            throw e;
        }
        //新增成功,开始调用静态页面合成方法
        getAllHtmls();
        return result;
    }

    //<!--分页查询套餐数据,以及对应的关联检查组数据-->
    @Override
    public PageResult findAllSetmeal(QueryPageBean queryPageBean) {
        //校验
        long total = 0;
        List<Setmeal> result = null;
        try {
            Integer currentPage = queryPageBean.getCurrentPage();
            Integer pageSize = queryPageBean.getPageSize();
            PageHelper.startPage(currentPage, pageSize);
            Page<Setmeal> allSetmeal = setmealDao.findAllSetmeal(queryPageBean.getQueryString());
            total = allSetmeal.getTotal();
            result = allSetmeal.getResult();
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return new PageResult(total, result);
    }

    //<!--//删除指定套餐,需要删除三张表中的数据-->
    @Override
    public Result deleteSetmeal(int id) {
        Result result = null;
        try {
            setmealDao.deleteCroupAndSetmeal(id);
            int a = setmealDao.deleteOrder(id);
            setmealDao.deleteSetmeal(id);
            result = new Result(true, "删除套餐成功了");
        } catch (Exception e) {
            e.printStackTrace();
            result = new Result(false, "删除套餐失败");
        }
        return result;
    }

    //修改检查组,需要先把中间表相关数据干掉,再插入中间表数据
    @Override
    public Result updateSetmeal(Setmeal setmeal, Integer[] list) {
        Result result = null;
        try {
            //先把中间表数据干掉
            setmealDao.deleteCroupAndSetmeal(setmeal.getId());
            //开始从新插入中间表
            if (list != null && list.length > 0) {
                setmealDao.addSetmealAddCheckGroup(list, setmeal.getId());
            }
            //查询出老的名字,判断是否更换了图片,若更换了然后在容器中干掉老的名字
            String n = setmealDao.findImgById(setmeal.getId());
            if (n != setmeal.getImg()) {
                //说明不是原来的,干掉原来的
                if (n != null) {
                    jedisPool.getResource().srem(RedisConstant.MINCOLLECTION, n);
                    //删掉云端老图片图片
                    QiniuUtils.deleteFileFromQiniu(n);
                }
                //吧新的图片名字存到小容器里,
                saveRedis(setmeal.getImg());

            }
            //开始修改数据
            setmealDao.updateSetmeal(setmeal);
            result = new Result(true, "修改成功", n);
        } catch (Exception e) {
            e.printStackTrace();
            result = new Result(true, "修改失败");
        }
        return result;
    }

    //不分页查询所有数据
    public Result findSetmeal() {
        List<Setmeal> list = setmealDao.findSetmeal();
        return new Result(true, "查询成功", list);
    }

    //根据id显示相关套餐组的详细信息
    public Result findDetailedById(int id) {
        /*分析:根据这个id先查询setmeal数据,再查询检查组数据,在查询检查项数据,关联查询
        注意事项:对象不能为空,集合不能为空,判断id不不存在是否会报错,没有设计内容修改*/
        //先查询套餐表
        Setmeal setmeal = setmealDao.findSetmealById(id);
        return new Result(true, "查询成功", setmeal);
    }

    @Override
    public void test() {
        System.out.println("你好");
        System.out.println(outPutPath);
    }
    /*统计分析套餐预约情况占比*/
    @Override
    public Result getSetmealReport() {
        /*分析:前台需要套餐名称数组,另一个套餐和套餐数量的数组
        查询操作无需校验,查询一个即可
        * */
        Map map = new HashMap<>();
        List<Map<String,Object>> list=setmealDao.getSetmealReport();
        map.put("setmealCount",list);
        List list2=new ArrayList();
        for (Map<String, Object> stringObjectMap : list) {
            list2.add(stringObjectMap.get("name"));
        }
        map.put("setmealNames",list2);
        return new Result(true,MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS,map);
    }

    //保存到redis方法抽取
    private void saveRedis(String picName) {
        jedisPool.getResource().sadd(RedisConstant.MINCOLLECTION, picName);
    }
    //提取一个同时生成列表,同时生成详细信息页面的方法
    public  void getAllHtmls(){
        //生成之前查询所有数据
        //TODO 这个find方法可能有异常
        List<Setmeal> list = setmealDao.findSetmeal();
        //开始生成列表静态页面
        HashMap map = new HashMap();
        map.put("setmealList",list);
        getCreateHtml("mobile_setmeal.ftl","m_setmeal.html",map);
        //开始生成列表详细页面
        for (Setmeal setmeal : list) {
            HashMap hashMap = new HashMap();
            hashMap.put("setmeal",setmeal);
            getCreateHtml("mobile_setmeal_detail.ftl","setmeal_detail_"+setmeal.getId()+".html",hashMap);
        }

    }
    //提取一个最终合成成静态页面的方法
    public void getCreateHtml(String templateName, String hemlPageName, Map map){
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        try {
            Template template = configuration.getTemplate(templateName);
            //构造输出流
            FileWriter out = new FileWriter(new File(outPutPath + "/" + hemlPageName));
            //输出文件
            template.process(map,out);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
    }



}
